<template>
  <el-dialog :title="dialogTitle" :visible.sync="showDialog_" custom-class='dialog_right MkAddCategory dialogScroll_add' top="0%" @close='closeDialog("addForm")' @open='openDialog'>
    <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight- 200)+'px'}]">
    <el-form :model="addForm.formItem" :rules="addForm.rules" ref="addForm" label-width="80px">
      <input type="text" style="display:none" />
      <el-form-item label="分类名称" prop='name'>
        <el-input v-model="addForm.formItem.name" placeholder='请输入分类名称（必填）' @change="changeField('addForm','addForm','name')" size="" :maxlength=6></el-input>
      </el-form-item>
      <el-form-item label="上级分类" v-if="parentObj">
        {{parentObj.name}}
      </el-form-item>
      <el-form-item label="上级分类" v-if="currentObj && currentObj.parentName">
        {{currentObj.parentName}}
      </el-form-item>
      <el-form-item label="是否展示" prop='status'>
        <el-radio-group v-model="addForm.formItem.status">
          <el-radio label="ENABLE">是</el-radio>
          <el-radio label="DISABLE">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop='weight'>
        <el-input v-model="addForm.formItem.weight" placeholder='请输入排序（必填）' :maxlength=7></el-input>
      </el-form-item>
      <el-form-item label="描述" prop='describe'>
        <el-input v-model="addForm.formItem.describe"  type="textarea" placeholder='请输入描述' :maxlength=20 :rows="3"></el-input>
      </el-form-item>
      <el-form-item label="分类图片" prop="imageId">
        <el-upload class="avatar-uploader":data="{'width':400,'height':200}" :action="'/upload/images.json'" list-type="picture-card" :on-success="handleSuccess" :on-remove="handleRemove" :file-list="fileList" :before-upload="beforeCoverUpload" accept=".jpeg, .jpg, .png, .gif" name="images">
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <p style="color:#83a0a5;font-size:14px;">建议上传400*200规格的图片</p>
      </el-form-item>
    </el-form>
    </el-scrollbar>
    <div slot="footer" class="dialog-footer footerStyle">
      <el-button type="primary" class="btn-primary" element-loading-text="提交中" @click='submitForm("addForm")' v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
      <el-button type='primary' class='btn-cancel' @click="showDialog_ = false" size=''>取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import serveService from '../../services/serve'
  import {mapState} from 'vuex'
  export default {
    name: 'MkAddCategory',
    components: {
    },
    props: ['showDialog', 'parentObj', 'currentObj'],
    computed: mapState({
      bodyHeight: state => state.global.bodyHeight,
    }),
    methods: {
      handleRemove(file, fileList) {
        let fileId = file.fileId ? file.fileId : file.response.data[0].fileId;
        serveService.deleteFileServer({ fileId: fileId }, data => {
          this.$message.success('删除成功');
          this.addForm.formItem.imageId = '';
        })
      },
      beforeCoverUpload() {
      },
      handleSuccess(res, file) {
        this.addForm.formItem.imageId = res.data[0].fileId + '';
      },
      changeField(form, formName, field) {
        this[form].formItem[field] = this[form].formItem[field].trim();
        this.$refs[formName].validateField(field);
      },
      closeDialog(formName) {
        this.$refs[formName].resetFields();
        this.$emit('closeDialog', this.isRefresh);
        var form = this.addForm.formItem;
        form.name = '';
        form.weight = '';
        form.describe = '';
        form.status = 'ENABLE';
        form.imageId = '';
        form.parentId = '';
        form.id = '';
        this.fileList = [];
      },
      openDialog() {
        this.isRefresh = false;
        this.clickSubmitBtn = false;
        this.dialogTitle = '添加分类';
        if (this.currentObj) {
          this.dialogTitle = '编辑分类';
          var form = this.addForm.formItem;
          var currentObj = this.currentObj;
          form.name = currentObj.name;
          form.status = currentObj.status;
          form.id = currentObj.id;
          form.weight = currentObj.weight;
          form.describe = currentObj.des;
          if (currentObj.icon) {
            form.imageId = currentObj.iconId;
            this.fileList = [{ url: currentObj.icon, fileId: currentObj.iconId }];
          }
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (!this.currentObj) {
              this.addForm.formItem.parentId = this.parentObj ? this.parentObj.id : 1;
            }
            if(this.addForm.formItem.status=='ENABLE'){
            	if(!this.addForm.formItem.imageId){
                this.$message.warning('请上传图片');
                return;
              }
            }
            if (!this.clickSubmitBtn) {
              this.fullscreenLoading = true;
              this.clickSubmitBtn = true;
              if (this.currentObj) {
                serveService.editServeServer(this.addForm.formItem, (data) => {
                  this.$message.success('编辑成功');
                  this.isRefresh = true;
                  this.showDialog_ = false;
                  this.fullscreenLoading = false;
                }, (data) => {
                  this.fullscreenLoading = false;
                  this.clickSubmitBtn = false;
                })
              }
              else {
                serveService.addServeServer(this.addForm.formItem, (data) => {
                  this.$message.success( '添加成功');
                  this.isRefresh = true;
                  this.showDialog_ = false;
                  this.fullscreenLoading = false;
                }, (data) => {
                  this.fullscreenLoading = false;
                  this.clickSubmitBtn = false;
                })
              }
            }
          }
        })
      }
    },
    watch: {
      showDialog: function(value) {
        this.showDialog_ = value;
      }
    },
    data() {
      var validateSort = (rule, value, callback) => {
        let val = (value + '').trim();
        if (val === '') {
          callback(new Error('请输入排序'));
        } else {
          let reg = /^[1-9]\d{0,3}$/;
          if (!reg.test(val)) {
            callback(new Error('只能输入整数，最多4位'));
          }
          callback();
        }
      };
      return {
        fileList: [],
        dialogTitle: '',
        clickSubmitBtn: false,
        fullscreenLoading: false,
        isRefresh: false,
        showDialog_: this.showDialog,
        addForm: {
          formItem: {
            name: '',
            status: 'ENABLE',
            imageId: '',
            parentId: '',
            id: '',//编辑用到
            weight:'',
            describe:'',
          },
          rules: {
            name: [
              { required: true, message: '请输入分类名称', tigger: 'change' }],
            weight: [
              {validator: validateSort,tigger: 'change' }]
          }
        }
      }
    }
  }
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less'>
  @import '../../assets/style/main.less';
  .MkAddCategory {
    .avatar-uploader {
      .el-upload-list--picture-card {
        position: absolute;
        z-index: 10;
      }
      .el-upload:hover {
        border-color: @primaryColor;
      }
      .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        height: 146px;
        width: 146px;
      }
      .el-upload--picture-card {
        background: white;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 146px;
        height: 146px;
        line-height: 146px;
        text-align: center;
      }
    }
  }
</style>
